import 'package:bloc/bloc.dart';
import 'package:flutter_test_demo/database/index.dart';
import 'package:flutter_test_demo/model/index.dart';
import 'package:flutter_test_demo/utils/index.dart';

import 'state.dart';

class ShopCartBlocCubit extends Cubit<ShopCartBlocState> {
  ShopCartBlocCubit() : super(ShopCartBlocState().init()) {
    queryCartList();
  }

  void queryCartList() async {
    List<CartModel> cartGoodsList = await MethodDao.queryCartGoodsList();
    print("购物车商品：：${cartGoodsList.length}");
    emit(state.clone()..cartGoodsList = cartGoodsList);
  }

  void clearCart() async {
    if(state.cartGoodsList.isEmpty) {
      return ;
    }
    await MethodDao.deleteAllCartGoodsList();
    List<GoodsListModel> goodsList = await MethodDao.queryGoodsList();
    if(goodsList.isNotEmpty) {
      for (var e in goodsList) {
        e.goodsQty = 0;
        await MethodDao.updateGoodsList(e);
      }
    }
    queryCartList();
  }

  num totalPrice() {
    num total = 0;
    if(state.cartGoodsList.isNotEmpty) {
      for (var e in state.cartGoodsList) {
        if(e.shopCartQty != null && e.shopCartQty! > 0) {
          total = total + (e.shopCartQty! * (e.shopCartPrice ?? 0));
        }
      }
    }
    return total;
  }

  void addCount(CartModel model) async {
    if(model.shopCartQty != null) {
      model.shopCartQty = model.shopCartQty! + 1;
      await MethodDao.updateCartGoodsList(model);
      updateGoodsCount(model, model.shopCartQty ?? 0);
    }
    emit(state.clone());
  }

  void subCount(CartModel model) async {
    if(model.shopCartQty != null) {
      model.shopCartQty = model.shopCartQty! - 1;
      if(model.shopCartQty == 0) {
        await MethodDao.deleteCartGoodsList(model);
        updateGoodsCount(model, model.shopCartQty ?? 0);
        queryCartList();
        return ;
      }
      await MethodDao.updateCartGoodsList(model);
      updateGoodsCount(model, model.shopCartQty ?? 0);
    }
    emit(state.clone());
  }

  void updateGoodsCount(CartModel model, int qty) async {
    List<GoodsListModel> goodsList = await MethodDao.queryGoodsList();
    if(goodsList.isNotEmpty) {
      GoodsListModel? data = goodsList.firstWhereOrNull((e) => e.goodsCode == model.shopCartCode);
      if(data != null) {
        data.goodsQty = qty;
        await MethodDao.updateGoodsList(data);
      }
    }
  }

  Future<void> submitOrder(String payWay) async {
    await saveOrder(payWay);
    await saveOrderItem();
    // Get.back();
    clearCart();
    // Get.toNamed(RouterName.orderPage);
  }

  Future<void> saveOrder(String payWay) async {
    String random = RandomUtil.createRandom(100000);
    DateTime d = DateTime.now();
    String orderDoc = '${d.year}${d.month.toString().padLeft(2, '0')}${d.day.toString().padLeft(2, '0')}$random';
    String orderTime = d.toString().substring(0, 19);
    OrderModel model = OrderModel();
    model.orderDoc = orderDoc;
    model.orderTime = orderTime;
    model.totalPrice = totalPrice();
    model.payWay = payWay;
    await MethodDao.insertOrder(model);

    List<OrderModel> list = await MethodDao.queryOrderList();
    if(list.isNotEmpty) {
      OrderModel? data = list.firstWhereOrNull((e) => e.orderDoc == model.orderDoc);
      if(data != null) {
        state.foreign = data.orderId;
      }
    }
  }

  Future<void> saveOrderItem() async {
    if(state.cartGoodsList.isNotEmpty) {
      for (var e in state.cartGoodsList) {
        OrderItemModel model = OrderItemModel();
        model.orderGoodsName = e.shopCartName;
        model.orderGoodsCode = e.shopCartCode;
        model.orderGoodsPrice = e.shopCartPrice;
        model.orderGoodsQty = e.shopCartQty;
        model.orderId = state.foreign;
        await MethodDao.insertOrderItem(model);
      }
    }
  }

}

extension IterableExtension<E> on Iterable<E> {
  E? firstWhereOrNull(bool Function(E) test) {
    for (final element in this) {
      if (test(element)) return element;
    }
    return null;
  }
}
